package com.gvsoft.communication.client.status;

import com.gvsoft.communication.common.model.order.KeepOrder;
import com.gvsoft.communication.client.Client;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgClient
 * Author: zhaoqiubo
 * Date: 15/8/8
 * Time: 上午10:49
 * Desc: 维持链路线程，当获得服务端分配的令牌后启动。
 * 如果链路维护收不到服务端的响应一定次数后，则触发客户端对服务端的重连。
 */
public class KeepChannelThread extends Thread {

    private final static Logger logger = LogManager.getLogger("client");
    private Client client;
    private boolean isInterrupt = true;

    public KeepChannelThread(Client client, String name) {
        this.setName(name);
        this.client = client;
    }

    public void setInterrupt() {
        this.isInterrupt = true;
        super.interrupt();
    }

    public void run() {

        while (isInterrupt) {
            if (client.getnSocket().isActive()) {
                if (client.getKOrderMapSize() >= client.getCfg().getKeepTimeoutCount()) {
                    client.getnSocket().setReconnect();
                    logger.info("服务器通道无响应,K指令缓冲区已满，进行重连……服务器状态设置为：【" + client.getClientStatus() + "】");

                }
                try {
                    //构建链路维护指令对象
                    KeepOrder keepOrder = new KeepOrder(client.getToken());
                    client.getnSocket().write(keepOrder);
                    client.addKeepOrder(keepOrder);
                } catch (Exception e) {
                    if (!client.getnSocket().isClosed()) {
                        client.getnSocket().setReconnect();
                        logger.error("网络交互中断，开始进行重连……服务器状态设置为：【" + client.getClientStatus() + "】");
                    }
                }
            }
            try {
                Thread.sleep(client.getCfg().getKeepAliveCycle() * 1000);
//                Thread.sleep(80) ;//测试每秒10个包
            } catch (InterruptedException e) {
                logger.error("KeepChannelThread is interrupted:"+e.getMessage());
            }
        }

    }
}

